package com.pronosticnews.client.admin.view.listSport;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.cell.client.ImageCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.CellPreviewEvent.Handler;
import com.google.gwt.view.client.HasData;
import com.pronosticnews.client.admin.resources.PronosticnewsAdminMessages;
import com.pronosticnews.client.admin.resources.PronosticnewsAdminResources;
import com.pronosticnews.shared.model.SportDto;

import fr.ysa.services.config.FiltreDto;
import fr.ysa.services.config.FiltreDto.TYPE;
import fr.ysa.services.config.ValueFiltreDto;
import fr.ysa.services.config.ValueFiltreDto.OPERATION;

public class ListSportViewImpl extends Composite implements ListSportView {
	
	private final Integer logoColumnSize = 100;
	private final Integer logoSize = 70;
	
	interface ListSportUiBinder extends UiBinder<Widget, ListSportViewImpl> {
	}
	
	private class LogoColumn extends Column<SportDto, String> {

		public LogoColumn() {
			super(new ImageCell(){
				@Override
				public void render(Context context, String value,
						SafeHtmlBuilder sb) {
					if (value != null) {
						super.render(context, value, sb);
					}					
				}	
			});
		}

		@Override
		public String getValue(SportDto sport) {
			return com.google.gwt.core.client.GWT.getHostPageBaseURL()+"image/?id=" + sport.getLogo()+"&width="+logoSize;
		}
		
	}
	
	private class NameColumn extends Column<SportDto, String> {
		public NameColumn() {
			super(new TextCell());
		}

		@Override
		public String getValue(SportDto sport) {
			return sport.getNom();
		}
	}

	@UiField
	SimplePager pager;

	@UiField
	DataGrid<SportDto> table;

	 @UiField
	 ListBox lstItemsPage;

	@UiField
	DialogBox suppressionBox;

	@UiField
	ListBox lstFiltreNom;

	@UiField
	TextBox txtFiltreNom;

	@UiField
	DisclosurePanel panel_list_filter;
	
	@UiField(provided=true)
	PronosticnewsAdminResources res;
	
	@UiField
	DockLayoutPanel dock;

	interface ClosurePanelFiltreStyle extends CssResource {
		String filtre_panel_close();

		String filtre_panel_open();
	}

	@UiField
	VerticalPanel panel_list_header;
	
	private Presenter presenter;

	private PronosticnewsAdminMessages messages;

	public ListSportViewImpl() {
		messages = GWT.create(PronosticnewsAdminMessages.class);
		res = GWT.create(PronosticnewsAdminResources.class);
		res.cssDeleteBoxElemTable().ensureInjected();
		res.cssList().ensureInjected();
		initWidget(GWT.<ListSportUiBinder> create(ListSportUiBinder.class)
				.createAndBindUi(this));
		
		initFiltresName();
		createLogoColumn();
		createNameColumn();

		table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		AsyncHandler columnSortHandler = new AsyncHandler(table);
		table.addColumnSortHandler(columnSortHandler);

		table.addCellPreviewHandler(new Handler<SportDto>() {

			@Override
			public void onCellPreview(CellPreviewEvent<SportDto> event) {
				if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_DELETE) {
					suppressionBox.center();
				}
			}
		});
		
		panel_list_filter.addOpenHandler(new OpenHandler<DisclosurePanel>() {			
			@Override
			public void onOpen(OpenEvent<DisclosurePanel> event) {
				panel_list_filter.setStyleName(res.cssList().filtre_panel_open());		
				dock.setWidgetSize(panel_list_header, panel_list_filter.getOffsetHeight()+40);
				dock.forceLayout();
			}
		});	
		
		panel_list_filter.addCloseHandler(new CloseHandler<DisclosurePanel>() {			
			@Override
			public void onClose(CloseEvent<DisclosurePanel> event) {
				panel_list_filter.setStyleName(res.cssList().filtre_panel_close());	
				dock.setWidgetSize(panel_list_header, 70);
				dock.forceLayout();
			}
		});			
	}

	private void initFiltresName() {
		lstFiltreNom.addItem("égale", ValueFiltreDto.OPERATION.EQUAL.name());
		lstFiltreNom.addItem("contient", ValueFiltreDto.OPERATION.LIKE.name());
	}

	@UiHandler({ "txtFiltreNom" })
	void onFilterKeyPress(KeyPressEvent event) {
		if (event.getCharCode() == KeyCodes.KEY_ENTER) {
			sendFiltres();
		}
	}

	@UiHandler({"lstFiltreNom"})
	void onLstFilterChange(ChangeEvent event) {
		sendFiltres();
	}
	
	@UiHandler("bt_clear_filtrer")
	void onClickClearFiltre(ClickEvent event) {
		txtFiltreNom.setText("");
		presenter.updateFiltreRequete(null);
	}

	private void sendFiltres() {
		List<FiltreDto> filtres = new ArrayList<FiltreDto>();
		filtres.add(getFiltreNom());
		presenter.updateFiltreRequete(filtres);
	}

	private FiltreDto getFiltreNom() {
		int operationIndex = lstFiltreNom.getSelectedIndex();
		String operation = lstFiltreNom.getValue(operationIndex);
		FiltreDto filtre = new FiltreDto();
		filtre.setName(SportDto.VALUE_NAME.nom.name());
		filtre.setType(TYPE.STRING);
		ValueFiltreDto valueFiltreDto = new ValueFiltreDto();
		valueFiltreDto.setValue(txtFiltreNom.getText());
		valueFiltreDto.setOperation(OPERATION.valueOf(operation));
		filtre.addValue(valueFiltreDto);
		return filtre;
	}

	private void createLogoColumn() {
		Column<SportDto, String> logoColumn = new LogoColumn();
		logoColumn.setSortable(false);
		table.addColumn(logoColumn,"");
		table.setColumnWidth(logoColumn, logoColumnSize.toString()+"px");
	}	
	
	
	private void createNameColumn() {
		Column<SportDto, String> nameColumn = new NameColumn();
		nameColumn.setDataStoreName(SportDto.VALUE_NAME.nom.name());
		nameColumn.setSortable(true);
		table.addColumn(nameColumn, messages.sport());
		table.getColumnSortList().push(nameColumn);
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public HasData<SportDto> getHasData() {
		return table;

	}

	@Override
	public ColumnSortList getColumnSortList() {
		return table.getColumnSortList();
	}

	@UiHandler("btValiderSuppression")
	void onClickValiderSuppression(ClickEvent event) {
		suppressionBox.hide();
		presenter.supprimeSelected();
	}

	@UiHandler("btAnnulerSuppression")
	void onClickAnnulerSuppression(ClickEvent event) {
		suppressionBox.hide();
	}

	@UiHandler("lstItemsPage")
	void itemsPageValueChange(ChangeEvent event) {
		if (event.getSource().equals(lstItemsPage)) {
			int selectedIndex = lstItemsPage.getSelectedIndex();
			int nbItemsPage = Integer.parseInt(lstItemsPage
					.getValue(selectedIndex));
			table.setPageSize(nbItemsPage);
		}
	}

	@Override
	public void setSport(int debut, List<SportDto> result) {
		table.setRowData(debut, result);
	}

	@Override
	public void setRowCount(Integer result) {
		table.setRowCount(result, true);
	}

}
